package team.yidong.fenda.wx.controller;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import team.yidong.fenda.payUtil.*;
import team.yidong.fenda.service.WxOrderService;
import team.yidong.fenda.utils.*;
import team.yidong.fenda.wx.Service.WxUserService;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by xuanlong on 2017/12/5.
 */
@Controller
public class WxPayController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    WxPrePayUtil wxPrePayUtil;
    @Autowired
    WxLoginUtil wxLoginUtil;
    @Autowired
    WxUserService wxUserService;
    @Autowired
    WxOrderService wxOrderService;
    @Autowired
    FalvAskPayUtil falvAskPayUtil;

    /**
     * 医院支付
     *
     * @param code
     * @param request
     * @param total_fee
     * @return
     */
    @RequestMapping("/wx/pay")
    @ResponseBody
    public Map<String, Object> wxPrePay(@RequestParam String code, HttpServletRequest request, @RequestParam String total_fee) {
        String spbill_create_ip = IpUtil.getIpAddr(request);
        System.out.println("ip地址是:" + spbill_create_ip + "****");
        String string = wxLoginUtil.Get("https://api.weixin.qq.com/sns/jscode2session?appid=wx697ed96969c6707f&secret=9f1cc13b4ecbc55ae5c9bd0285ddd8b8&js_code=" + code + "&grant_type=authorization_code");
        JSONObject jsonObject = JSONObject.fromObject(string);
        String openid = jsonObject.getString("openid");
        return wxPrePayUtil.prePay(openid, request, total_fee);
    }

    /**
     * 医院版提问支付成功回调
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/wx/paySuccess")
    @ResponseBody
    public void paySuccess(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        //sb为微信返回的xml
        String notityXml = sb.toString();
        String resXml = "";

        Map map = PayUtil.doXMLParse(notityXml);
        String returnSign = (String) map.get("sign");
        String returnCode = (String) map.get("return_code");


        //sign不参与签名
        map.remove("sign");
        if ("SUCCESS".equals(returnCode)) {
            //验证签名是否正确

            if (PayUtil.sign(PayUtil.createLinkString(map), WxPayConfig.key, "utf-8").toUpperCase().equals(returnSign)) {
                /**此处添加自己的业务逻辑代码start**/
                String endTime = (String) map.get("time_end");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = simpleDateFormat.parse(endTime);
                endTime = simpleDateFormat1.format(date);
                wxOrderService.addWxOrder((String) map.get("out_trade_no"), (String) map.get("appid"), (String) map.get("bank_type"), Integer.parseInt((String) map.get("total_fee")), endTime);
                /**此处添加自己的业务逻辑代码end**/
                //通知微信服务器已经支付成功
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            } else {

            }

        } else {

            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        System.out.println(resXml);
        System.out.println("微信支付回调数据结束");


        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();


    }

    //商家给用户分钱
    @RequestMapping("/giveMasterMoney")
    @ResponseBody
    public void giveMasterMoney() {


    }

    /**
     * 法律提问支付
     */
    @RequestMapping("/wx/falvPay")
    @ResponseBody
    public Map<String, Object> wxFalvPrePay(@RequestParam String code, HttpServletRequest request, @RequestParam String total_fee) {
        String string = wxLoginUtil.Get("https://api.weixin.qq.com/sns/jscode2session?appid=wxeebd2de131ff2f5f&secret=58ea4ec32afb62696d8782554e78ee33&js_code=" + code + "&grant_type=authorization_code");
        JSONObject jsonObject = JSONObject.fromObject(string);
        String openid = jsonObject.getString("openid");
        return falvAskPayUtil.prePay(openid, request, total_fee);
    }

    @RequestMapping("/wx/falvPaySuccess")
    @ResponseBody
    public void falvPaySuccess(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        //sb为微信返回的xml
        String notityXml = sb.toString();
        String resXml = "";

        Map map = PayUtil.doXMLParse(notityXml);
        String returnSign = (String) map.get("sign");
        String returnCode = (String) map.get("return_code");


        //sign不参与签名
        map.remove("sign");
        if ("SUCCESS".equals(returnCode)) {
            //验证签名是否正确

            if (PayUtil.sign(PayUtil.createLinkString(map), FalvAskPayConfig.key, "utf-8").toUpperCase().equals(returnSign)) {
                /**此处添加自己的业务逻辑代码start**/
                String endTime = (String) map.get("time_end");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = simpleDateFormat.parse(endTime);
                endTime = simpleDateFormat1.format(date);
                wxOrderService.addWxOrder((String) map.get("out_trade_no"), (String) map.get("appid"), (String) map.get("bank_type"), Integer.parseInt((String) map.get("total_fee")), endTime);
                /**此处添加自己的业务逻辑代码end**/
                //通知微信服务器已经支付成功
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            } else {

            }

        } else {

            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }

        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();


    }
}

